package com.heze.xunhuan.service.impl;

import com.heze.xunhuan.dto.BindPhoneDTO;
import com.heze.xunhuan.dto.WechatLoginDTO;
import com.heze.xunhuan.entity.User;
import com.heze.xunhuan.exception.BusinessException;
import com.heze.xunhuan.service.AuthService;
import com.heze.xunhuan.service.UserService;
import com.heze.xunhuan.utils.JwtUtil;
import com.heze.xunhuan.utils.SecurityContextUtil;
import com.heze.xunhuan.utils.WechatUtil;
import com.heze.xunhuan.vo.LoginVO;
import com.heze.xunhuan.vo.UserVO;
import cn.hutool.json.JSONObject;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * 认证服务实现类
 *
 * @author heze-xunhuan
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class AuthServiceImpl implements AuthService {

    private final WechatUtil wechatUtil;
    private final UserService userService;
    private final JwtUtil jwtUtil;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public LoginVO wechatLogin(WechatLoginDTO dto) {
        // 调用微信API获取openid和session_key
        JSONObject sessionInfo = wechatUtil.code2Session(dto.getCode());
        String openid = sessionInfo.getStr("openid");
        String unionid = sessionInfo.getStr("unionid");
        String sessionKey = sessionInfo.getStr("session_key");
        
        if (openid == null) {
            throw new BusinessException("微信登录失败，请重试");
        }
        
        // 获取用户信息
        String nickname = dto.getUserInfo() != null ? dto.getUserInfo().getNickName() : "微信用户";
        String avatar = dto.getUserInfo() != null ? dto.getUserInfo().getAvatarUrl() : null;
        Integer gender = dto.getUserInfo() != null ? dto.getUserInfo().getGender() : 0;

        // 创建或更新用户
        User user = userService.createOrUpdateUser(openid, unionid, nickname, avatar, gender);
        
        // 生成Token
        String token = jwtUtil.generateToken(user.getId(), user.getOpenid());
        
        // 构建返回对象
        LoginVO loginVO = new LoginVO();
        loginVO.setToken(token);
        loginVO.setUserInfo(userService.getUserInfo(user.getId()));
        
        return loginVO;
    }

    @Override
    public String bindPhone(BindPhoneDTO dto) {
        Long userId = SecurityContextUtil.getCurrentUserId();
        if (userId == null) {
            throw new BusinessException(401, "未登录");
        }
        
        return userService.bindPhone(userId, dto.getCode());
    }

    @Override
    public String refreshToken(String token) {
        if (!jwtUtil.isRefreshToken(token)) {
            throw new BusinessException(400, "无效的刷新Token");
        }
        
        Long userId = jwtUtil.getUserIdFromToken(token);
        String openid = jwtUtil.getOpenidFromToken(token);
        
        if (userId == null || openid == null) {
            throw new BusinessException(401, "Token无效");
        }
        
        return jwtUtil.generateToken(userId, openid);
    }
}

